package com.example.youjingjing.electronicbalance;


import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;

import com.example.youjingjing.electronicbalance.javaandroid.DBXException;
import com.example.youjingjing.electronicbalance.javaandroid.DSRESTConnection;
import com.example.youjingjing.electronicbalance.javaandroid.TDataSet;
import com.example.youjingjing.electronicbalance.javaandroid.TJSONObject;
import com.example.youjingjing.electronicbalance.service.DownloadListener;
import com.example.youjingjing.electronicbalance.utils.JsonUtils;
import com.example.youjingjing.electronicbalance.widge.MainActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;


/**
 * Created by youjingjing on 2017/8/3.
 */

public class MyService extends Service {
    SparseArray<String> array;
    private MyAscyncTaskDemo myAscyncTaskDemo;
    public MyService() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(this, Connection.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("This is content title")
                .setContentText("This is content text")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .build();
        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent,  int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public IBinder onBind(Intent intent) {
        return myBind;
    }
    private MyBind myBind = new MyBind();

    public class MyBind extends Binder {
        public void startDownload() {
//            if (myAscyncTaskDemo == null) {
//                myAscyncTaskDemo = new MyAscyncTaskDemo(listener);
//            myAscyncTaskDemo.execute("123");
//                startForeground(1, getNotification("Downloading...", 0));
//                Toast.makeText(MyService.this, "Downloading...", Toast.LENGTH_SHORT).show();
//            }
            getServiceInfo("123");
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            int anHour = 8 * 60 * 60 * 1000; // 这是8小时的毫秒数
            long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
            Intent i = new Intent(getApplication(),MyService.class);
            PendingIntent pi = PendingIntent.getService(getApplicationContext(),0,i,0);
            alarmManager.cancel(pi);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
            Log.d("MyService", "startDownload executed");
        }

        public int getProgress() {
            Log.d("MyService", "getProgress executed");
            return 0;
        }
    }
    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotification(String title, int progress) {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if (progress >= 0) {
            // 当progress大于或等于0时才需显示下载进度
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder.build();
    }
    private DSRESTConnection getConnection(String host, int port) {

        DSRESTConnection conn = new DSRESTConnection();

        conn.setHost(host);

        conn.setPort(port);

        return conn;
    }

    private DownloadListener listener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            getNotificationManager().notify(1, getNotification("Downloading...", progress));
        }

        @Override
        public void onSuccess() {
            myAscyncTaskDemo = null;
            // 下载成功时将前台服务通知关闭，并创建一个下载成功的通知
            stopForeground(true);
            getNotificationManager().notify(1, getNotification("Download Success", -1));
            Toast.makeText(MyService.this, "Download Success", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            myAscyncTaskDemo = null;
            // 下载失败时将前台服务通知关闭，并创建一个下载失败的通知
            stopForeground(true);
            getNotificationManager().notify(1, getNotification("Download Failed", -1));
            Toast.makeText(MyService.this, "Download Failed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            myAscyncTaskDemo = null;
            Toast.makeText(MyService.this, "Paused", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            myAscyncTaskDemo = null;
            stopForeground(true);
            Toast.makeText(MyService.this, "Canceled", Toast.LENGTH_SHORT).show();
        }

    };
    public void getServiceInfo(String name){

        DSRESTConnection conn = getConnection("10.0.11.192",8080);

        GeneratedProxy.TPRT_DS_Interface ds = new GeneratedProxy.TPRT_DS_Interface(conn);

        try {
            TDataSet tDataSet = ds.GetUserAuthority(name);

            if(tDataSet.next()) {
                TJSONObject tjsonObject = tDataSet.asJSONObject();

//                        Log.e("run: ", "" +  tjsonObject.toString());

//                         Object userName = tjsonObject.get("UserName").value.getInternalObject();
//                        String authority = tjsonObject.get("UserAuthority").value.toString();

                JSONTokener jsonParser = new JSONTokener(JsonUtils.serialize(tjsonObject));

                JSONObject person = (JSONObject) jsonParser.nextValue();

                JSONArray elements = person.getJSONArray("Elements");

                array = new SparseArray<>();
                for (int i = 0; i < tDataSet.getColumns().size(); i++) {
                    JSONObject value = elements.getJSONObject(i);
                    JSONObject value1 = value.getJSONObject("value");
                    JSONArray elements1 = value1.getJSONArray("Elements");
                    JSONObject jsonObject = elements1.getJSONObject(0);
                    String n = jsonObject.get("value").toString();
                    Log.e( "run: ", "门店号：" +n);
                    array.put(i,n);
                }

//                        user.updateAll("password = ? and name = ?", "2","12");

//                        User user1 = new User();
//                        user.setName("");
//                        user.setPassword("");
//                        ContentValues values = new ContentValues();
//                        values.put("password", "12");
////                      DataSupport.updateAll(User.class,values);
//                        DataSupport.updateAll(User.class, values, "password = ? and name = ?", "2","12");

//        DataSupport.delete(User.class,2);
//                        if (user.isSaved()) {
//                            user.delete();
//                        }


//                    Dataset.Builder builder = new Dataset.Builder();
//                    Dataset dataset = builder.build();

            }else{
                Log.d("1", "没有数据 " );
            }
        } catch (DBXException e) {
            Log.e("1", "连接失败 " );
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
